<!-- 任务再委托 -->
<template>
  <view>
    <u-form
      :model="model"
      :rules="rules"
      ref="form"
      labelPosition="top"
      labelWidth="auto"
      :labelStyle="{
        fontSize: '14px',
        color: '#B2B2B2',
        lineHight: '20px',
      }"
    >
      <view class="basic-style">
        <view class="basic-title basic-border">基本信息</view>
        <u-form-item label="单据编号" prop="billNo" required>
          <u--input v-model="model.billNo" disabled></u--input>
        </u-form-item>
        <u-form-item label="申请时间" prop="createTime" required>
          <u--input v-model="model.createTime" disabled></u--input>
        </u-form-item>
        <u-form-item label="申请人" prop="handlerId" required>
          <h-select-person-input
            style="width: 100%"
            disabled
            v-model="model.handlerId"
            placeholder="请选择申请人"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            objectField="model.handlerId"
          ></h-select-person-input>
        </u-form-item>
        <u-form-item label="申请部门" prop="handlerDeptId" required>
          <h-select-depart-input
            disabled
            v-model="model.handlerDeptId"
            :departName="model.handlerDeptId_dictText"
            placeholder="请选择部门"
            border="surround"
            style="width: 100%"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            :title.sync="model.handlerDeptId_dictText"
          ></h-select-depart-input>
        </u-form-item>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border pt-1">项目信息</view>
        <u-form-item label="项目名称" prop="projectId" required>
					<h-select-project-distribution-input
						:projectStatus="'2'"
						:proDisabled="true"
						:isContractManager="true"
						v-model="model.projectId"
						objectField="model.projectId"
						style="width: 100%"
						placeholder="请选择项目名称"
						border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
						@input="onChangeProjectName"
					></h-select-project-distribution-input>
        </u-form-item>
        <u-form-item label="项目编号" prop="finalNo">
          <u--input disabled placeholder="请输入项目编号" v-model="model.finalNo"></u--input>
        </u-form-item>
        <u-form-item label="经营团队" prop="teamName">
          <h-select-team-input
            disabled
            style="width: 100%"
            v-model="model.teamName"
            objectField="model.teamName"
            placeholder="请选择经营团队"
            border="surround"
            :tdlx="1"
          />
        </u-form-item>
        <u-form-item label="项目承接人" prop="undertaker">
          <h-select-person-input-popup
            disabled
            v-model="model.undertaker"
            style="width: 100%"
            placeholder="请选择项目承接人"
            searchPlaceholder="请输入"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-select-person-input-popup>
        </u-form-item>
        <u-form-item label="立项日期" prop="projectEstablishDate">
          <h-time-select
            disabled
            mode="datetime"
            v-model="model.projectEstablishDate"
            placeholder="请选择立项日期"
            border="surround"
            suffixIcon="calendar-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-time-select>
        </u-form-item>
        <u-form-item label="签订单位" prop="signUnit">
          <h-select-company-input-popup
            disabled
            style="width: 100%"
            v-model="model.signUnit"
            commercialType="1"
            placeholder="请选择公司"
            border="surround"
          ></h-select-company-input-popup>
        </u-form-item>
        <u-form-item label="业绩归属年度" prop="year">
          <h-select-input-tag
            disabled
            class="w-100"
            v-model="model.year"
            objectField="model.year"
            placeholder="请选择业绩归属年度"
            border="surround"
            dictName="yjgsnd"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="业主单位" prop="ownerUnit">
          <h-select-customer-input-popup
            disabled
            style="width: 100%"
            v-model="model.ownerUnit"
            objectField="model.ownerUnit"
            commercialType="1"
            placeholder="请选择业主单位"
            border="surround"
          ></h-select-customer-input-popup>
        </u-form-item>
        <u-form-item label="联系人" prop="contacts">
          <h-select-input-tag
            disabled
            class="w-100"
            v-model="model.contacts"
            objectField="model.contacts"
            placeholder="请选择联系人"
            border="surround"
            :dictName="cust_lxr"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="联系方式" prop="contactTel">
          <u--input disabled placeholder="请输入联系方式" v-model="model.contactTel"></u--input>
        </u-form-item>
        <u-form-item label="项目所在地址" prop="areaCode" :borderBottom="false">
          <h-select-address-input
            disabled
            style="width: 100%"
            v-model="model.areaCode"
            placeholder="请选择项目地址"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-select-address-input>
        </u-form-item>
        <u-form-item label="项目详细地址" prop="projectAddress" :borderBottom="false">
          <u--input disabled placeholder="请输入项目详细地址" v-model="model.projectAddress"></u--input>
        </u-form-item>
        <u-form-item label="项目来源" prop="projectSource">
          <h-select-input-tag
            disabled
            class="w-100"
            v-model="model.projectSource"
            objectField="model.projectSource"
            placeholder="请选择项目来源"
            border="surround"
            dictName="xmly_type"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="预计合同额(元)" prop="estimatedContractAmount">
          <u--input
            disabled
            type="number"
            v-number-normal
            placeholder="请输入预计合同额"
            v-model="model.estimatedContractAmount"
          ></u--input>
        </u-form-item>
        <u-form-item label="预计合同额大写" prop="estimatedContractcapitalChineseAmount">
          <u--input disabled placeholder="请输入预计合同额大写" v-model="model.estimatedContractcapitalChineseAmount"></u--input>
        </u-form-item>
        <u-form-item label="立项事由及说明" prop="establishReason">
          <u--textarea
            disabled
            maxlength="500"
            :confirm-type="null"
						count
            v-model="model.establishReason"
            placeholder="请输入立项事由及说明"
          ></u--textarea>
        </u-form-item>
        <view>
          <view class="basic-title basic-border">项目附件</view>
          <view class="py-1 space-y-1" style="width: 100%">
            <view style="color: red">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
            <file-list v-if="model.attachment" v-model="model.attachment"></file-list>
						<view v-else>
							<u-empty
								mode="data"
								text="暂无项目附件"
								icon="/static/empty/data.png"
							></u-empty>
						</view>
          </view>
        </view>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border pt-1">需分配任务信息</view>
        <u-form-item label="任务编号" prop="taskId" required>
					<h-select-task-file-input-popup
            :projectId="model.projectId"
            :api="erpOmcProjectTaskFinalList"
            v-model="model.taskId"
            class="w-100"
            :disabled="!model.projectId"
            :placeholder="model.projectId ? '请选择任务编号' : '请先选择项目'"
            searchPlaceholder="请输入任务编号"
            border="surround"
            label="billNo"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            @realChange="onTaskIdInput"
            :customParams="{
              changeStatus: '!changing',
              distributionType: 'producting,finish',
            }"
            @select="model.taskDescription = $event.taskDescription"
					></h-select-task-file-input-popup>
        </u-form-item>
        <u-form-item label="业务分类" prop="categoryName">
          <u--input disabled placeholder="请输入业务分类" v-model="model.categoryName"></u--input>
        </u-form-item>
        <u-form-item label="合同占比(%)" prop="contractRate">
          <u--input disabled type="number" v-number-normal placeholder="请输入合同占比" v-model="model.contractRate"></u--input>
        </u-form-item>
        <u-form-item label="合同分配额(元)" prop="contractAmount">
          <u--input disabled type="number" v-number-normal placeholder="请输入合同分配额" v-model="model.contractAmount"></u--input>
        </u-form-item>
        <u-form-item label="切割合同额(元)" prop="cutContractAmount">
          <u--input disabled type="number" v-number-normal placeholder="请输入合同分配额" v-model="model.cutContractAmount"></u--input>
        </u-form-item>
        <u-form-item label="生产团队" prop="productTeam">
          <h-select-team-input
            disabled
            style="width: 100%"
            v-model="model.productTeam"
            objectField="model.productTeam"
            placeholder="请选择生产团队"
            border="surround"
            :tdlx="2"
          />
        </u-form-item>
        <!-- <u-form-item
          label="生产公司"
          prop="productCompanyId"
          :borderBottom="false"
        >
          <h-select-company-input
            disabled
            style="width: 100%"
            v-model="model.productCompanyId"
            border="surround"
            placeholder="请选择生产公司"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{color: '#B2B2B2'}"
          ></h-select-company-input>
          </u-form-item> -->
        <u-form-item label="需分配合同额(元)" prop="separateContractAmount" :borderBottom="false" required>
          <h-money-input
            placeholder="请输入需分配合同额"
            v-model="model.separateContractAmount"
						:max="originalContractAmount"
            @blur="handleChangeSeparateContractAmount"
          ></h-money-input>
        </u-form-item>
        <u-form-item label="需分配切割合同额(元)" prop="needCutContractAmount" :borderBottom="false" required>
          <h-money-input
            placeholder="请输入需分配切割合同额"
            v-model="model.needCutContractAmount"
						:max="cutTheContractAmount"
            @blur="handleChangeSeparateContractAmount"
          ></h-money-input>
        </u-form-item>
        <u-form-item label="是否作废" prop="isCancel" :borderBottom="false" required>
          <h-dict-radio v-model="model.isCancel" dictName="YES_OR_NO" @change="handleChangeIsCancel"></h-dict-radio>
        </u-form-item>
        <u-form-item label="说明" prop="reason">
          <u--textarea maxlength="500" :confirm-type="null" count v-model="model.reason" placeholder="请输入说明"></u--textarea>
        </u-form-item>
        <view class="basic-title basic-border">任务附件</view>
        <view class="py-1 space-y-1" style="width: 100%">
          <view style="color: red">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
          <h-upload-file v-model="model.file" :isIcon="false"></h-upload-file>
          <file-list v-if="model.file" v-model="model.file" :isDelete="true"></file-list>
        </view>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border pt-1">新增分配任务信息</view>
        <view class="space-y-1 py-1">
          <u-button size="small" type="primary" @click="handleAddMember">新增</u-button>
        </view>
        <u-collapse v-if="formData && formData.length">
          <u-collapse-item :title="item.categoryName" v-for="(item, index) in formData" :key="index">
            <FormInfo :item="item" :index="index" @edit="handleEditForm" @remove="handleRemoveForm" @copy="handleCopyForm" />
          </u-collapse-item>
        </u-collapse>
        <u-popup mode="bottom" :show="showFormModal">
          <TaskForm
            ref="dataForm"
            :estimatedContractAmount="model.estimatedContractAmount"
            :separateContractAmount="model.separateContractAmount"
            :index="index"
            @submit="handleFormSubmit"
            @close="closeFormModal"
            :model="model"
          />
        </u-popup>
      </view>
			
			<view class="basic-style">
        <view class="basic-title basic-border">需分配款项信息</view>
        <view v-for="(item, index) in receivablePaymentList" :key="index">
          <ErpOmcTaskRedistributionPaymentFormInfo 
						:item="item" 
						:showKxxx="item.shouldPayFlag == '1'"
						:index="index"
						@edit="handleEditFormC" 
						@remove="handleRemoveFormC"
						@copy="handleCopyFormC" 
						:disabled="true"
          />
        </view>
        <u-popup mode="bottom" :show="showFormModalC" :closeOnClickOverlay="false">
          <ErpOmcTaskRedistributionPaymentForm
						:estimatedContractAmount="model.estimatedContractAmount"
						:separateContractAmount="model.separateContractAmount"
						ref="dataFormC"
						:index="formDataCIndex"
						:redistributionDtList="paymentTaskList"
						:projectId="model.projectId"
						@submit="handleFormSubmitC"
						@close="closeFormModalC" />
        </u-popup>
			</view>

      <view class="space-x-1 px-1 btn_position">
        <u-button :disabled="isSubmit" type="primary" :plain="true" text="保存" @click="onDraft"></u-button>
        <u-button :disabled="isSubmit" type="primary" text="保存并提交" @click="onSubmit"></u-button>
      </view>
      <view style="height: 100rpx"></view>
    </u-form>
    <u-toast ref="uToast"></u-toast>
    <ProcessNodeConfiguration ref="processConfig" @ok="onOk"></ProcessNodeConfiguration>
  </view>
</template>

<script>
import { mapState } from 'vuex'
import moment from 'moment'
import { erpProgressTemplateDtList, queryDistributionProjectList, erpOmcProjectTaskFinalList } from '@/api/index'
import { gainBillNo, add, info, edit, queryPageList, erpOmcProjectQueryById } from '@/api/project/ErpOmcTaskRedistributionForm'
import http from '@/utils/request/index'
import fileList from '@/pages/synergy/components/fileList.vue'
import TaskForm from './components/TaskForm.vue'
import FormInfo from './components/TaskFormInfo.vue'
import ErpOmcTaskRedistributionPaymentFormInfo from './components/ErpOmcTaskRedistributionPaymentFormInfo.vue'
import ErpOmcTaskRedistributionPaymentForm from './components/ErpOmcTaskRedistributionPaymentForm.vue'
import Decimal from 'decimal.js'
import ProcessNodeConfiguration from '@/components/ProcessNodeConfiguration/ProcessNodeConfiguration.vue' // 流程节点配置人员选择弹窗
export default {
  name: 'ErpOmcTaskRedistributionForm',
  components: {
    fileList,
    TaskForm,
    FormInfo,
    ProcessNodeConfiguration,
		ErpOmcTaskRedistributionPaymentFormInfo,
		ErpOmcTaskRedistributionPaymentForm
  },
  data() {
    return {
			basicFormC: {},
			showFormModalC: false,
			receivablePaymentList: [], // 需分配款项信息
			paymentTaskList: [], // 任务委托数据
      taskInfoObj: {id: ''},
      originalContractAmount: 0,
      cutTheContractAmount:0, // 原切割合同额
      isSubmit: false,
      flowCode: 'dev_erp_omc_task_redistribution_001',
      beanName: 'erpOmcTaskRedistributionServiceImpl',
      formUrl: '/erp/omc/taskredistribution/modules/ErpOmcTaskRedistributionForm',
      formUrlMobile: '/pages/synergy/ErpOmcTaskRedistributionForm',
      processId: '1557666877169283074',
      queryDistributionProjectList,
      erpOmcProjectTaskFinalList,
      taskProgressFields: {
        节点名称: 'nodeName',
        节点进度: 'nodeProgress',
        完成状态: 'taskCompleteStatus_dictText',
        完成时间: 'completeTime',
      },
      templateDataList: [],
      cust_lxr: 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=0',
      backUpProvisionBroad: '',
      showBusinessSegment: false,
      exportTeamId: '',
      flag: false,
      index: null,
			formDataCIndex: null,
      showFormModal: false,
      confirmModal: false,
      loading: false,
      id: '',
      exportWarehouseList: [],
      foldWarehouseList: [],
      dataSource2: [],
      basicForm: {},
      formData: [],
      progressNodeVoList: [],
      model: {
        billNo: '',
        createTime: '',
        handlerId: '',
        handlerDeptId: '',
        projectId: '',
        finalNo: '',
        teamName: '',
        undertaker: '',
        projectEstablishDate: '',
        signUnit: '',
        year: '',
        ownerUnit: '',
        contacts: '',
        contactTel: '',
        areaCode: '',
        projectAddress: '',
        projectSource: '',
        estimatedContractAmount: '',
        estimatedContractcapitalChineseAmount: '',
        establishReason: '',
        taskId: '',
        categoryName: '',
        contractRate: '',
        contractAmount: '',
        cutContractAmount:'',
        productTeam: '',
        productCompanyId: '',
        separateContractAmount: '',
        needCutContractAmount:'',
        isCancel: '',
        reason: '',
        file: null,
        purchaseFile: null,
      },
      rules: {
        projectId: [{ required: true, message: '请选择项目名称!', pattern: '[^ \x22]+' }],
        separateContractAmount: [{ required: true, message: '请输入需分配合同额!' }],
        needCutContractAmount: [{ required: true, message: '请输入需分配切割合同额!' }],
        isCancel: [{ required: true, message: '请选择是否作废!' }],
        taskId: [{ required: true, message: '请选择任务编号!' }],
      },
    }
  },
  onLoad({ id }) {
    this.id = id || ''
  },
  created() {
    if (this.id) {
      this.initInfo()
    } else {
      this.initForm()
      this.initBillNo()
    }
    // this.initBuyerInfo()
  },
  computed: {
    ...mapState(['userInfo']),
    showFlowSubmitButton() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return true
        }
      }
      return false
    },
  },
  methods: {
		// 获取需分配的款项信息
		getReceivablePaymentList(taskId, mainId, type) {
			if (!taskId) {
				this.receivablePaymentList = []
				return
			}
			var params = {
				taskId: taskId
			}
			if (mainId) {
				params.mainId = mainId
			}
			if (type) {
				params.type = type
			}
			http.get('/api/erp/task/erpOmcTaskRedistribution/queryReceivablePayment', params).then(res => {
				if (res.success) {
					if (res.result && res.result.length > 0) {
						res.result.map((value, index) => {
							res.result[index].taskId_dictText = '' // 首先款项关联任务字段默认为空
							// 遍历planTaskVoList数组赋值给taskId_dictText
							res.result[index].taskId_dictText = value.planTaskVoList && value.planTaskVoList.length ? (value.planTaskVoList.map((obj) => { return obj.categoryName }).join(',')) : '';
						})
						this.receivablePaymentList = res.result
					} else {
						this.receivablePaymentList = []
					}
				} else {
					this.receivablePaymentList = []
				}
			}).catch(() => {
				this.receivablePaymentList = []
			})
		},
		// 获取需分配款项信息中的款项关联任务信息
    getPaymentTaskList(event, id) {
      this.paymentTaskList = []
      if (this.model.isCancel != '1') {
        // 当是否作废为是时则往paymentTaskList中添加一条原始任务信息
        let arr = this.formData && this.formData.length ? JSON.parse(JSON.stringify(this.formData)) : []
        if (id) {
          let obj = {
            id,
            categoryCode: event.categoryCode, // 任务分类编码
            categoryName: event.categoryName, // 任务分类名称
            contractRate: event.contractRate, // 合同占比
            contractAmount: event.contractAmount, // 合同分配额
            cutContractAmount: event.cutContractAmount, // 切割分配额
            productTeam: event.productTeam, // 生产团队
            productCompanyId: event.productCompanyId, // 生产公司
            productTeam_dictText: event.productTeam_dictText, // 生产团队
            teamLeader: event.teamLeader, // 生产团队
            teamLeader_dictText: event.teamLeader_dictText, // 生产团队
            taskDescription: event.taskDescription // 任务说明
          }
          arr.push(obj)
        }
        this.paymentTaskList = arr
      } else {
        this.paymentTaskList = this.formData && this.formData.length ? JSON.parse(JSON.stringify(this.formData)) : []
      }
    },
		handleEditFormC([item, index]) {
			this.basicFormC = { ...item }
			this.formDataCIndex = index
			this.showFormModalC = true
			this.$nextTick(() => {
				this.openFormModalC()
			})
		},
		handleRemoveFormC(data) {
			this.receivablePaymentList = this.receivablePaymentList.filter((i) => i !== data)
		},
		closeFormModalC() {
			this.$refs.dataFormC.reset()
			this.basicFormC = {}
			this.formDataCIndex = null
			this.showFormModalC = false
		},
		openFormModalC() {
			this.$refs.dataFormC.basicForm = Object.assign({},this.basicFormC)
			this.$refs.dataFormC.formDataC = this.basicFormC.planTaskVoList || []
		},
		handleCopyFormC([item, index]) {
			this.receivablePaymentList.push({
        ...item,
			})
			this.$refs.uToast.show({
				message:'复制成功!'
			})
		},
		addFormC() {
			this.formDataCIndex = null
			this.basicFormC = {}
			this.showFormModalC = true
		},
		/**
		 * 子表单新增点击确认
		 */
		handleFormSubmitC([data, index]) {
			this.showFormModalC = false
			if (typeof index === 'number') {
        this.$set(this.receivablePaymentList, index, data)
			} else {
        this.receivablePaymentList.push(data)
			}
		  // this.initBuyerInfo()
		},
		
    // 如果选择是，则需分配合同额自动变更为原始的合同分配额（元），合同分配额自动变为0
    handleChangeIsCancel(val) {
			var _this = this
      if (val === '1') {
				if (_this.receivablePaymentList && _this.receivablePaymentList.length > 0) {
					uni.showModal({
						title: '是否确定此选择?',
						content: '选择为是，会清除需分配款项信息中的关联任务，是否继续？',
						success (res) {
							if (res.confirm) {
					      _this.$set(_this.model, 'separateContractAmount', _this.originalContractAmount)
                _this.$set(_this.model, 'needCutContractAmount', _this.cutTheContractAmount)

					      _this.$set(_this.model, 'contractAmount', 0)
					      _this.$set(_this.model, 'cutContractAmount', 0)
					      _this.getPaymentTaskList(_this.taskInfoObj, _this.taskInfoObj.id)
								_this.handleChangeSeparateContractAmount('isCancel')
								// 当有需分配款项信息时，需要清空原有的任务
								// 对比款项中的任务,删除原有的任务
								_this.receivablePaymentList.forEach((item, index) => {
									if (item && item.shouldPayFlag !='1' && item.planTaskVoList && item.planTaskVoList.length > 0) {
										item.planTaskVoList.forEach((item1, ind) => {
											// 循环遍历新增分配任务信息是否与任务中的taskId相互匹配，匹配不上删除任务信息
											if (_this.formData && _this.formData.length > 0) {
												_this.formData.forEach((item2, ind2) => {
													if (item1.taskId != item2.id) {
														_this.receivablePaymentList[index].planTaskVoList.splice(ind, 1);
													}
												})
											} else {
												// 没有新增的任务信息，则删除所有的任务
												_this.receivablePaymentList[index].planTaskVoList = [];
											}
										})
									}
								})
								_this.receivablePaymentList.map((value, index) => {
									_this.receivablePaymentList[index].taskId_dictText = '' // 首先款项关联任务字段默认为空
									// 遍历planTaskVoList数组赋值给taskId_dictText
									_this.receivablePaymentList[index].taskId_dictText = value.planTaskVoList && value.planTaskVoList.length ? (value.planTaskVoList.map((obj) => { return obj.categoryName }).join(',')) : '';
								})
							} else if (res.cancel) {
					      _this.$set(_this.model, 'isCancel', '0')
								_this.handleChangeSeparateContractAmount('isCancel')
							}
						}
					});
				} else {
					_this.$set(_this.model, 'separateContractAmount', _this.originalContractAmount)
          _this.$set(_this.model, 'needCutContractAmount', _this.cutTheContractAmount)

					_this.$set(_this.model, 'contractAmount', 0)
					_this.$set(_this.model, 'cutContractAmount', 0)
					_this.handleChangeSeparateContractAmount('isCancel')
				}
      } else {
				_this.model.isCancel = val
				if (_this.receivablePaymentList && _this.receivablePaymentList.length > 0) {
					_this.getPaymentTaskList(_this.taskInfoObj, _this.taskInfoObj.id)
				}
				_this.handleChangeSeparateContractAmount('isCancel')
      }
    },
    handleChangeSeparateContractAmount(arg) {
      // 需分配合同额不可大于需分配任务中原始的合同分配额
      if (Number(this.model.separateContractAmount) > Number(this.originalContractAmount)) {
        this.model.separateContractAmount = this.originalContractAmount
      }
            // 需分配切割合同额不可大于需分配任务中原始的切割合同额
            if (Number(this.model.needCutContractAmount) > Number(this.cutTheContractAmount)) {
        this.model.needCutContractAmount = this.cutTheContractAmount
      }
			if (arg != 'isCancel') {
				// 如果需分配合同额等于初始的合同分配额，则是否作废自动变为是
				if (Number(this.model.separateContractAmount) === Number(this.originalContractAmount)) {
				  this.$set(this.model, 'isCancel', '1')
				} 

        if (Number(this.model.needCutContractAmount) === Number(this.cutTheContractAmount)) {
          this.$set(this.model, 'isCancel', '1')
        }
        // else {
				//   // this.$set(this.model, 'isCancel', '0')
				// }
			}
      if (this.originalContractAmount && !isNaN(this.model.separateContractAmount)) {
        this.$set(this.model, 'contractAmount', Number(this.originalContractAmount - this.model.separateContractAmount).toFixed(2))
        // 输入数字后，合同分配额会自动减少对应的金额，且需分配任务的合同占比也相应变小。需分配合同额不可大于需分配任务中原始的合同分配额。
        if (this.model.estimatedContractAmount) {
          this.$set(this.model, 'contractRate', ((this.model.contractAmount / this.model.estimatedContractAmount) * 100).toFixed(2))
        }
      }

      if (this.cutTheContractAmount && !isNaN(this.model.needCutContractAmount)) {
        this.$set(this.model, 'cutContractAmount', Number(this.cutTheContractAmount - this.model.needCutContractAmount).toFixed(2))
      }
    },
    // 提交流程成功
    onOk() {
      this.$refs.uToast.show({
        message: '提交成功',
        type: 'success',
        complete() {
          if (getCurrentPages().length > 1) {
            uni.navigateBack()
          } else {
            uni.reLaunch({
              url: '/pages/home/home',
            })
          }
        },
      })
    },
    getFieldsValue(key, value) {
      if (key === '是否关联任务节点' || key === '是否关联进度') {
        return value === '1' ? '是' : '否'
      }
      return value
    },
    // 选择项目名称
    async onChangeProjectName(event) {
      this.taskInfoObj = { id: '' } // 数据置空
			this.receivablePaymentList = [] // 款项置空
      this.getPaymentTaskList(this.taskInfoObj, this.taskInfoObj.id)
      if (!event) {
        this.$set(this.model, 'projectName', '') // 项目名称
        this.$set(this.model, 'bail', '') // 保证金
        this.$set(this.model, 'finalNo', '') // 项目编号
        this.$set(this.model, 'teamName', '') // 经营团队
        this.$set(this.model, 'undertaker', '') // 项目承接人
        this.$set(this.model, 'projectEstablishDate', '') // 立项日期
        this.$set(this.model, 'signUnit', '') // 签订单位
        this.$set(this.model, 'year', '') // 业绩归属年度
        this.$set(this.model, 'ownerUnit', '') // 业主单位
        this.$set(this.model, 'contacts', '') // 联系人
        this.$set(this.model, 'contactTel', '') // 联系方式
        this.$set(this.model, 'areaCode', '') // 项目所在地址
        this.$set(this.model, 'projectAddress', '') // 项目所在详细地址
        this.$set(this.model, 'projectSource', '') // 项目来源
        this.$set(this.model, 'estimatedContractAmount', '') // 预计合同额
        this.$set(this.model, 'estimatedContractcapitalChineseAmount', '') // 预计合同额大写
        this.$set(this.model, 'establishReason', '') // 立项事由及说明
        this.$set(this.model, 'attachment', '') // 项目附件

        this.$set(this.model, 'categoryName', '') // 业务分类
        this.$set(this.model, 'categoryCode', '') // 业务分类
        this.$set(this.model, 'contractRate', '') // 合同占比(%)
        this.$set(this.model, 'contractAmount', '') // 合同分配额(元)
        this.$set(this.model, 'cutContractAmount', '') // 切割合同额(元)
        this.$set(this.model, 'needCutContractAmount', '') // 切割合同额(元)

        this.$set(this.model, 'productTeam', '') // 生产团队
        this.$set(this.model, 'productCompanyId', '') // 生产公司
        this.$set(this.model, 'taskId', '') // 任务编号
        this.progressNodeVoList = [] // 清空款项进度
        return false
      }
      this.$set(this.model, 'projectName', event.projectName) // 项目名称
      this.$set(this.model, 'finalNo', event.finalNo) // 项目编号
			this.$set(this.model, 'teamName', event.oldTeamId ? event.oldTeamId : event.teamName) // 经营团队
      this.$set(this.model, 'undertaker', event.undertaker) // 项目承接人
      this.$set(this.model, 'projectEstablishDate', event.projectEstablishDate) // 立项日期
      this.$set(this.model, 'signUnit', event.signUnit) // 签订单位
      this.$set(this.model, 'year', event.year) // 业绩归属年度
      this.$set(this.model, 'ownerUnit', event.ownerUnit) // 业主单位
      this.$set(this.model, 'contacts', event.contacts) // 联系人
      this.$set(this.model, 'contactTel', event.contactTel) // 联系方式
      this.$set(this.model, 'areaCode', event.areaCode) // 项目所在地址
      this.$set(this.model, 'projectAddress', event.projectAddress) // 项目所在详细地址
      this.$set(this.model, 'projectSource', event.projectSource) // 项目来源
      this.$set(this.model, 'estimatedContractAmount', event.estimatedContractAmount) // 预计合同额
      this.$set(this.model, 'estimatedContractcapitalChineseAmount', event.estimatedContractcapitalChineseAmount) // 预计合同额大写
      this.$set(this.model, 'establishReason', event.establishReason) // 立项事由及说明
      this.$set(this.model, 'attachment', event.attachment) // 项目附件
      this.cust_lxr = "erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id='" + event.ownerUnit + "'"

      this.$set(this.model, 'categoryName', '') // 业务分类
      this.$set(this.model, 'categoryCode', '') // 业务分类
      this.$set(this.model, 'contractRate', '') // 合同占比(%)
      this.$set(this.model, 'contractAmount', '') // 合同分配额(元)
      this.$set(this.model, 'cutContractAmount', '') // 切割合同额(元)

      this.$set(this.model, 'productTeam', '') // 生产团队
      this.$set(this.model, 'productCompanyId', '') // 生产公司
      this.$set(this.model, 'taskId', '') // 任务编号
			this.$set(this.model, 'separateContractAmount', '') // 需分配合同额(元)
      this.$set(this.model, 'needCutContractAmount', '') // 需切割合同额(元)

			this.$set(this.model, 'isCancel', '') // 是否作废
			this.originalContractAmount = null
      this.cutTheContractAmount = null
			this.formData = [] // 任务置空
    },
    // 选择任务编号
    onTaskIdInput(event) {
      if (!event) {
        this.$set(this.model, 'categoryName', '') // 业务分类
        this.$set(this.model, 'categoryCode', '') // 业务分类
        this.$set(this.model, 'contractRate', '') // 合同占比(%)
        this.$set(this.model, 'contractAmount', '') // 合同分配额(元)
        this.$set(this.model, 'cutContractAmount', '') // 切割合同额(元)
        this.$set(this.model, 'productTeam', '') // 生产团队
        this.$set(this.model, 'productCompanyId', '') // 生产公司
        this.taskInfoObj = { id: '' } // 数据置空
				this.receivablePaymentList = [] // 款项置空
        this.getPaymentTaskList(this.taskInfoObj, this.taskInfoObj.id)
        return false
      }
			this.getReceivablePaymentList(this.model.taskId, null, '1') // 获取需分配的款项信息
      this.$set(this.model, 'categoryCode', event.categoryCode) // 业务分类编码
      this.$set(this.model, 'categoryName', event.categoryName) // 业务分类
      this.$set(this.model, 'contractRate', event.contractRate) // 合同占比(%)
      this.$set(this.model, 'contractAmount', event.contractAmount) // 合同分配额(元)
      this.$set(this.model, 'cutContractAmount', event.cutContractAmount) // 合同分配额(元)
      this.$set(this.model, 'separateContractAmount', '') // 需分配合同额(元)
      this.$set(this.model, 'needCutContractAmount', '') // 需切割合同额(元)
      // this.$set(this.model, 'contractAmount', event.contractAmount) // 合同分配额(元)
      this.originalContractAmount = event.contractAmount // 合同分配额(元)
      this.cutTheContractAmount = event.cutContractAmount // 切割合同额(元)
			this.queryPaymentListByProjectId(event.id) // 获取款项进度列表
      this.$set(this.model, 'productTeam', event.productTeam) // 生产团队
      this.$set(this.model, 'productCompanyId', event.productCompanyId) // 生产公司
      this.taskInfoObj = event
      this.getPaymentTaskList(event, event.id)
    },

    // 获取款项进度列表
    queryPaymentListByProjectId(taskId) {
      this.progressNodeVoList = []
      http.get('/api/erp/omc/task/erpOmcTaskDistribution/queryTaskPaymentList', { taskId }).then((res) => {
        if (res.success) {
          this.progressNodeVoList = res.result
        }
      })
    },
    // 编辑获取任务进度列表
    queryTaskNodeListByMainId(id) {
      if (!id) {
        return false
      }
      this.templateLoading = true
      this.templateDataList = []
      http
        .get('/api/erp/omc/task/erpOmcTaskDistribution/queryTaskNodeListByMainId', { id })
        .then((res) => {
          if (res.success) {
            this.templateDataList = res.result
          }
        })
        .finally(() => {
          this.templateLoading = false
        })
    },

    // 选择实施部门
    onExecuteDepartInput(item) {
      if (!item.minister) {
        this.$set(this.model, 'minister', '')
        return false
      }
      // 赋值部门负责人
      http.get('/api/erpmng/sys/api/queryUsersByUsernames', { usernames: item[0].minister }).then((res) => {
        var idsArr = []
        var ids = ''
        if (res && res.length) {
          res.map((value) => {
            idsArr.push(value.empId)
          })
        }
        ids = idsArr.toString()
        this.$set(this.model, 'minister', ids)
      })
    },
    // 获取唯一随机数
    getRandomNum() {
      let date = new Date().valueOf() // 获取时间戳
      let txt = '1234567890' // 生成的随机机器码
      let len = 19 // 机器码有多少位
      let pwd = '' // 定义空变量用来接收机器码
      for (let i = 0; i < len; i++) {
        pwd += txt.charAt(Math.floor(Math.random() * txt.length)) // 循环机器码位数随机填充
      }
      return date + pwd
    },
    // 款项进度完善
    PerfectTaskChange(val) {
      this.progressNodeVoList.forEach((it, i) => {
        if (it.id === val.id) {
          this.progressNodeVoList.splice(i, 1, val)
        }
      })
    },
    // 获取任务进度
    getTaskNodeList(handlerType, id, projectId, taskId) {
      http
        .get('/api/erp/omc/task/erpOmcTaskDistributionChange/queryTaskNodeList', { handlerType, id, projectId, taskId, isChild: '0' })
        .then((res) => {
          if (res.success) {
            this.templateDataList = res.result
          }
        })
        .finally(() => {
          this.templateLoading = false
        })
    },
    // 获取款项进度
    getPaymentList(handlerType, id, projectId, taskId) {
      http
        .get('/api/erp/omc/task/erpOmcTaskDistributionChange/queryPaymentList', { projectId, id, taskId, handlerType })
        .then((res) => {
          if (res.success) {
            this.progressNodeVoList = res.result
          }
        })
        .finally(() => {
          this.templateLoading = false
        })
    },
    // 新增物料
    handleAddMember() {
      this.index = null
      this.showFormModal = true
			this.basicForm = {}
			this.openFormModal()
    },
    handleCopyForm([item, index]) {
      this.formData.push({
        ...item,
      })
      this.$u.toast('复制成功')
    },
    handleEditForm([item, index]) {
      this.basicForm = { ...item }
      this.index = index
      this.showFormModal = true
			this.openFormModal()
    },
    handleRemoveForm(data) {
       // 判断receivablePaymentList中的任务是否有含该id值，含了就需要删除
      if (this.receivablePaymentList && this.receivablePaymentList.length > 0) {
        this.receivablePaymentList.forEach((item, index) => {
          if (item && item.planTaskVoList && item.planTaskVoList.length > 0) {
            item.planTaskVoList.forEach((item1, ind) => {
              if (item1.taskId == data.id) {
                this.receivablePaymentList[index].planTaskVoList.splice(ind, 1);
              }
            })
          }
        })
        this.receivablePaymentList.map((value, index) => {
          this.receivablePaymentList[index].taskId_dictText = '' // 首先款项关联任务字段默认为空
          // 遍历planTaskList数组赋值给taskId_dictText
          this.receivablePaymentList[index].taskId_dictText = value.planTaskVoList && value.planTaskVoList.length ? (value.planTaskVoList.map((obj) => { return obj.categoryName }).join(',')) : '';
        })
      }
      this.formData = this.formData.filter((i) => i !== data)
      this.getPaymentTaskList(this.taskInfoObj, this.taskInfoObj.id)
    },
    closeFormModal() {
      this.$refs.dataForm.reset()
      this.basicForm = {}
      this.index = null
			this.showFormModal = false
    },
    openFormModal() {
      this.$nextTick(() => {
				this.$refs.dataForm.basicForm = this.basicForm
			})
    },
    addForm() {
      this.index = null
      this.showFormModal = true
    },
    /**
     * 子表单新增点击确认
     */
    handleFormSubmit([data, index]) {
      this.showFormModal = false
      if (typeof index === 'number') {
        this.$set(this.formData, index, { ...data })
        // 当是编辑的时候，查看需分配款项信息中的数据是否有绑定此任务，如果绑定则替换成新数据
        if (this.receivablePaymentList && this.receivablePaymentList.length > 0) {
          this.receivablePaymentList.forEach((item, index) => {
            if (item && item.planTaskVoList && item.planTaskVoList.length > 0) {
              item.planTaskVoList.forEach((item1, ind) => {
                if (item1.taskId == data.id) {
                  let obj = {
                    ...item1,
                    categoryName: data.categoryName,
                    taskDesc: data.taskDescription,
                    productTeam: data.productTeam,
                    productCompanyId: data.productCompanyId,
                    productTeamName: data.productTeam_dictText
                  }
                  // data.planId = item.planId
                  this.receivablePaymentList[index].planTaskVoList.splice(ind, 1, obj);
                }
              })
            }
          })
          this.receivablePaymentList.map((value, index) => {
            this.receivablePaymentList[index].taskId_dictText = '' // 首先款项关联任务字段默认为空
            // 遍历planTaskList数组赋值给taskId_dictText
            this.receivablePaymentList[index].taskId_dictText = value.planTaskVoList && value.planTaskVoList.length ? (value.planTaskVoList.map((obj) => { return obj.categoryName }).join(',')) : '';
          })
        }
      } else {
        this.formData.push(data)
      }
      this.getPaymentTaskList(this.taskInfoObj, this.taskInfoObj.id)
      // this.initBuyerInfo()
    },
    // 获取单据编号
    async initBillNo() {
      const res = await gainBillNo({ prefix: 'RWZFP', subSystemCode: '05' })
      this.model.billNo = res.result
      // this.model.bpmBizTitle = this.userInfo?.employee?.name + '-' + this.model.billNo //标题
    },
    // 初始化新增需要的数据
    initForm() {
      this.model.handlerId = this.userInfo.empId //当前登录人
      this.model.handlerDeptId = this.userInfo.deptId //当前登录人部门
      this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
    },
    async initInfo() {
      const response = await info({ id: this.id })
      const data = response?.result || {}
      for (const key in data) {
        this.$set(this.model, key, data[key])
      }
			this.getReceivablePaymentList(data.taskId, data.id, '2') // 获取需分配的款项信息
      this.cust_lxr = `erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=${data.ownerUnit}`
      erpOmcProjectQueryById({ id: this.model.projectId }).then((res) => {
        if (res.success) {
          var event = res.result
          this.$set(this.model, 'finalNo', event.finalNo) // 项目编号
        }
      })
      http.get('/api/erp/task/erpOmcTaskRedistributionDt/queryByMainId', { mainId: this.id }).then((response) => {
        this.$set(this, 'formData', response.result || [])
      })
      if (this.model && this.model.taskId) {
        http.get('/api/erp/omc/project/erpOmcProjectTask/queryById', { id: this.model.taskId }).then(res => {
          this.taskInfoObj = res.result
          this.getPaymentTaskList(this.taskInfoObj, this.taskInfoObj.id)
        })
      } else {
        this.taskInfoObj = { id: '' } // 数据置空
        this.getPaymentTaskList(this.taskInfoObj, this.taskInfoObj.id)
      }
      function parse(num) {
        return Number(num) || 0
      }
      this.originalContractAmount = new Decimal(parse(this.model.separateContractAmount)).plus(parse(this.model.contractAmount)).toNumber()
      this.cutTheContractAmount = new Decimal(parse(this.model.needCutContractAmount)).plus(parse(this.model.cutContractAmount)).toNumber()
    },
    validateForm() {
      return this.$refs.form.validate().then(async () => {
        if (this.model.isCancel === '1') {
          if (Number(this.model.separateContractAmount) !== Number(this.originalContractAmount)) {
            this.$u.toast('作废需分配任务时，请将需分配任务的所有合同额全部分配出去！')
            throw new Error('作废需分配任务时，请将需分配任务的所有合同额全部分配出去！')
          }
        } else {
          if (Number(this.model.separateContractAmount) === Number(this.originalContractAmount)) {
            this.$u.toast('需分配任务的所有合同额全部分配出去后，请作废该任务!')
            throw new Error('需分配任务的所有合同额全部分配出去后，请作废该任务!')
          }

          // if (Number(this.model.needCutContractAmount) === Number(this.cutTheContractAmount)) {
          //       const text = '需分配任务的所有切割合同额全部分配出去后，请作废该任务!'
          //       this.$u.toast(text);
          //       // this.$emit('unButtonDisable');
          //       throw new Error(text)
          //     }
        }
        


        // 列表中所有新增分配任务的合同占比之和应该等于需分配合同额占预计合同额的百分比
        let listTotal = this.formData.reduce((total, item) => {
          return total + (Number(item.contractRate) || 0)
        }, 0)
				listTotal = Math.floor(listTotal * 100) / 100
        const compareTotal = Number(Number((this.model.separateContractAmount / this.model.estimatedContractAmount) * 100).toFixed(2))
        if (listTotal !== compareTotal) {
          this.$u.toast(
            `列表中所有新增分配任务的合同占比之和应该等于需分配合同额占预计合同额的百分比！当前需分配合同额占预计合同额的百分比为${compareTotal}%`,
          )
          throw new Error('列表中所有新增分配任务的合同占比之和应该等于需分配合同额占预计合同额的百分比！')
        }

        // 列表中所有新增分配任务的合同分配额之和应该等于需分配合同额
        const listTotal2 = this.formData.reduce((total, item) => {
          return total + (Number(item.contractAmount) || 0)
        }, 0)
        if (listTotal2 !== Number(this.model.separateContractAmount)) {
          this.$u.toast('列表中所有新增分配任务的合同分配额之和应该等于需分配合同额！')
          throw new Error('列表中所有新增分配任务的合同分配额之和应该等于需分配合同额！')
        }
        
                    // 列表中所有新增分配任务的切割合同额之和应该等于需分配切割合同额
            const listTotal3 = this.formData.reduce((total, item) => {
              return total + (Number(item.cutContractAmount) || 0)
            }, 0)
            if (listTotal3 !== Number(this.model.needCutContractAmount)) {
              const text = '列表中所有新增分配任务的切割合同额之和应该等于需分配切割合同额!'
              this.$u.toast(text);
              // that.$emit('unButtonDisable');
              throw new Error(text)
            }

				// 这里判断需分配款项信息中的数据是否达到100%，如果达到则提交，否则提示需分配款项信息中的数据未达到100%
				if (!this.handleJudgePayment()) {
					const text = '请完善需分配款项信息'
					throw new Error('请完善需分配款项信息')
				}
        return Promise.resolve()
      })
    },
		// 判断需分配款项信息中的数据是否达到100%，如果达到则提交，否则提示需分配款项信息中的数据未达到100%
		handleJudgePayment() {
			var isTrue = true // true为通过，false为不通过
			var _this = this
			var text = ''
			if (this.receivablePaymentList && this.receivablePaymentList.length > 0) {
				// 判断是是否作废
				if (this.model.isCancel == '1') {
					// 判断新增任务是否有数据
					if (_this.formData && _this.formData.length > 0) {
						this.receivablePaymentList.forEach((item, index) => {
							if (item && item.shouldPayFlag != '1' && item.planTaskVoList && item.planTaskVoList.length > 0) {
								const array1 = item.planTaskVoList
                const array2 = _this.formData
                const matches = array1.every(item1 =>
                  array2.some(item2 => item1.taskId == item2.id)
                );
                if (!matches) {
                  text = '当选择"是否作废"为"是"，"需分配款项信息中的款项关联任务"需绑定"新增分配任务信息"中的任务！'
                  isTrue = false
                }
							}
						})
					} else {
						// 没有新增的任务信息，则删除所有的任务
						text = '请新增分配任务信息！'
						isTrue = false
					}
				}
				this.receivablePaymentList.forEach((item, index) => {
					if (item && item.planTaskVoList && item.planTaskVoList.length > 0) {
						// 判断item1中的 paymentMoney之和是否等于item中的isAllowDistributionMoney
						const listTotal = item.planTaskVoList.reduce((total, item1) => {
							const paymentMoney = Number(item1.paymentMoney) || 0;
							const decimalContractRate = new Decimal(paymentMoney);
							return total.plus(decimalContractRate);
						}, new Decimal(0)).toNumber(); // 解决浮点数导致两者不相等
						if (listTotal != item.isAllowDistributionMoney) {
							text = '需分配款项信息中，绑定的款项关联任务中，款项分配占比没有达到100%！'
							isTrue = false
						}
					} else {
						text = '剩余未生成应收需要分配给新任务！'
						isTrue = false // 没有任务时，不允许通过
					}
				})
			}
			if (!isTrue) {
				this.$u.toast(text)
			}
			return isTrue
		},
    // 获取流程列表
    getProcessList(id) {
      if (this.isSubmit) {
        this.$refs.processConfig.showPopup = true
        this.$refs.processConfig.formUrl = this.formUrl
        this.$refs.processConfig.formUrlMobile = this.formUrlMobile
        this.$refs.processConfig.flowCode = this.flowCode
        this.$refs.processConfig.edit(id, this.processId, this.beanName)
      }
    },
		async isBeginProcess() {
			return	http.get('/api/erp/omc/project/erpOmcProjectTask/checkTaskChangeAndStatusById', { id: this.model.taskId}).then( res => {
				if (res.success) {
					return Promise.resolve()
				} else {
					this.$refs.uToast.show({
						message: res.message,
						type: 'default',
						complete () {
							if (getCurrentPages().length > 1) {
								uni.navigateBack()
							} else {
								uni.reLaunch({
									url: '/pages/home/home'
								})
							}
							
						}
					})
					this.isSubmit = false
					return Promise.reject(res.message)
				}
			})
		},
    async onSubmit() {
      await this.validateForm()
      this.isSubmit = true
      try {
        this.loading = true
        var url = ''
        let method = ''
        if (this.id) {
          url = edit
          method = 'put'
        } else {
          url = add
          method = 'post'
        }
        const response = await url({
          ...this.model,
          redistributionDtList: this.formData, // 任务信息
          redistributionPlanVoList: this.receivablePaymentList || [] // 款项信息
        })
        if (response.success) {
          const verifyId = method === 'put' ? this.id : response.result; // 关键修改
          const result = await http.get('/api/erp/task/erpOmcTaskRedistribution/verify', { id: verifyId})
          if(!result.success) {
              uni.showToast({title: result.message,icon: 'none'}) 
              setTimeout(()=>{
                uni.navigateBack()
              },2000)
              return
          }
          var that = this
					await this.isBeginProcess()
          // 获取流程列表
          if (this.model.id) {
            this.getProcessList(this.model.id)
          } else {
            // 判断添加的时候是否有返回id值
            if (response.result) {
              this.getProcessList(response.result)
            }
          }
          this.$refs.uToast.show({
            message: response.message,
            type: 'default',
            complete() {
            },
          })
        }
      } finally {
        this.loading = false
      }
    },
    async onDraft() {
			var that = this
      // await this.validateForm()
			this.isSubmit = true
      try {
        this.loading = true
        var url = ''
        if (this.id) {
          url = edit
        } else {
          url = add
        }
        const response = await url({
          ...this.model,
          redistributionDtList: this.formData,
					redistributionPlanVoList: this.receivablePaymentList || [] // 款项信息
        })
        if (response.success) {
          this.$refs.uToast.show({
            message: response.message,
            type: 'default',
            complete () {
              that.isSubmit = false
              if (getCurrentPages().length > 1) {
                uni.navigateBack()
              } else {
                uni.reLaunch({
                  url: '/pages/home/home'
                })
              }
              
            }
          })
        }
      } finally {
        this.loading = false
      }
    },
  },
  watch: {
    formData(val) {
      if (!val) return

      function parse(num) {
        return Number(num) || 0
      }
      // 所有成员的预算工时之和
      this.model.expectWorkTime = val.reduce((total, item) => {
        return parse(new Decimal(parse(item.contractAmount)).plus(total).toNumber())
      }, 0)

      // 所有成员的人工成本之和
      this.model.workCost = val.reduce((total, item) => {
        return parse(new Decimal(parse(item.laborCost)).plus(total).toNumber())
      }, 0)
    }
  },
}
</script>

<style scoped lang="scss">
@import url('@/assets/inputStyle.scss');
.trip-form-data {
  ::v-deep {
    .u-form-item__body {
      padding-top: 2px;
      padding-bottom: 2px;
    }
  }
}
.checkbox-item {
  display: flex;
  align-items: center;
}
</style>
